import React, { useEffect, useRef, useState } from 'react'
import { Form, Input, message, Select, Slider, Cascader, Button } from 'antd'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { formItemLayout } from '../../const'
import { getChannelDetail, getProvinceList, getCityList, updateChannel, addChannel } from '../../../request/product'
import { actionCreators } from '../../../store'
import ENUMS from '../../../constants'
import './style.scss'

function EditChannel(props) {
  const { setBreadcrumb } = props
  const { getFieldDecorator, validateFields } = props.form
  const [provinceList, setProvinceList] = useState([])
  const [formData, setFormData] = useState({})
  const [isBtnLoading, setIsBtnLoading] = useState(false)
  const { Item } = Form
  const provinceLoadCount = useRef(1)

  useEffect(() => {
    const id = props.match.params.id
    setBreadcrumb([
      { name: '产品渠道', path: '/product/channel' },
      { name: id ? '编辑渠道' : '新增渠道' }
    ])
    getProvince().catch(e => console.log(e.message))
  }, [])

  useEffect(() => {
    const id = props.match.params.id
    if (provinceList.length > 0 && id && provinceLoadCount.current === 1) {
      getDetail(Number(id)).catch(e => console.log(e.message))
      provinceLoadCount.current += 1
    }
  }, [provinceList])

  const getDetail = async(id) => {
    const { code, message: errMsg, data } = await getChannelDetail({ id })
    if (code) {
      message.error(errMsg)
      return false
    }
    data.limit_age = [data.min_age, data.max_age]
    if (data.gsd_province_code) {
      const { code, message: errMsg, data: cityList } = await getCityList({ province_code: data.gsd_province_code })
      if (code) {
        message.error(errMsg)
        return false
      }
      const province = provinceList.map(item => {
        if (item.code === data.gsd_province_code) {
          item.children = cityList
        }
        return item
      })
      setProvinceList(province)
      data.gsd = [data.gsd_province_code, data.gsd_city_code]
    }
    setFormData(data)
  }

  const getProvince = async() => {
    const { code, message: errMsg, data } = await getProvinceList()
    if (code) {
      message.error(errMsg)
      return false
    }
    setProvinceList(data.map(item => ({ ...item, isLeaf: false })))
  }

  const loadData = async options => {
    if (!options.length) {
      return false
    }
    if (!provinceList.length) {
      return setTimeout(() => loadData(options), 1000)
    }
    const target = options[options.length - 1]
    target.loading = true
    const { code, message: errMsg, data } = await getCityList({ province_code: target.code })
    target.loading = false
    if (code) {
      message.error(errMsg)
      return false
    }
    target.children = data
    setProvinceList([...provinceList])
  }

  const onSubmit = () => {
    validateFields(async(err, values) => {
      if (err) {
        return false
      }
      const data = { ...values }
      if (formData.id) {
        data.id = formData.id
      }
      if (data.stock) {
        data.stock = Number(data.stock)
      }
      if (data.limit_age && data.limit_age.length === 2) {
        data.min_age = data.limit_age[0]
        data.max_age = data.limit_age[1]
      }
      if (data.gsd && data.gsd.length === 2) {
        data.gsd_province_code = data.gsd[0]
        data.gsd_city_code = data.gsd[1]
        const province = provinceList.find(item => item.code === data.gsd[0])
        if (province) {
          data.gsd_province = province.short_name
          const city = province.children.find(item => item.code === data.gsd[1])
          if (city) {
            data.gsd_city = city.short_name
          }
        }
      }
      delete data.gsd
      delete data.limit_age
      setIsBtnLoading(true)
      const { code, message: errMsg } = formData.id ? await updateChannel(data) : await addChannel(data)
      setIsBtnLoading(false)
      if (code) {
        message.error(errMsg)
        return false
      }
      message.success(formData.id ? '修改成功' : '添加成功')
      if (formData.id) {
        props.history.push('/product/channel')
      }
    })
  }

  return (
    <div className="edit-channel">
      <Form {...formItemLayout}>
        <h3>基础设置</h3>
        <Item label="套餐名称">
          {getFieldDecorator('name', {
            initialValue: formData.name || '',
            rules: [
              { required: true, message: '套餐名称不能为空' }
            ]
          })(
            <Input placeholder="请输入套餐名称"/>
          )}
        </Item>
        <Item label="运营商">
          {getFieldDecorator('isp', {
            initialValue: formData.isp || undefined,
            rules: [
              { required: true, message: '运营商不能为空' }
            ]
          })(
            <Select placeholder="选择运营商">
              {Object.keys(ENUMS.ISP).map(item =>
                (<Select.Option
                  value={Number(item)}
                  key={item}
                  label={ENUMS.ISP[item]}
                >
                  {ENUMS.ISP[item]}
                </Select.Option>)
              )}
            </Select>
          )}
        </Item>
        <Item label="产品编号">
          {getFieldDecorator('code', {
            initialValue: formData.code || '',
            rules: [
              { required: true, message: '产品编号不能为空' }
            ]
          })(
            <Input placeholder="请输入产品编号"/>
          )}
        </Item>
        <Item label="URL额外参数">
          {getFieldDecorator('url_param', {
            initialValue: formData.url_param || ''
          })(
            <Input placeholder="链接额外参数"/>
          )}
        </Item>
        {provinceList.length > 0 && (
          <Item label="归属地">
            {getFieldDecorator('gsd', {
              initialValue: formData.gsd || []
            })(
              <Cascader
                placeholder="选择归属地"
                fieldNames={{ label: 'short_name', value: 'code', children: 'children' }}
                options={provinceList}
                loadData={loadData}
                changeOnSelect={true}
              />
            )}
          </Item>
        )}
        <Item label="产地">
          {getFieldDecorator('made_in', {
            initialValue: formData.made_in || ''
          })(
            <Input placeholder="请输入产地"/>
          )}
        </Item>
        <h3>限制条件</h3>
        <Item label="单人开卡数量限制">
          {getFieldDecorator('limit_card_count', {
            initialValue: formData.limit_card_count || 5
          })(
            <Select placeholder="选择单人开卡数量">
              {Array.from({ length: 5 }).map((item, index) => (
                <Select.Option key={index + 1} value={index + 1}>{index + 1}</Select.Option>)
              )}
            </Select>
          )}
        </Item>
        <Item label="年龄限制(周岁)">
          {getFieldDecorator('limit_age', {
            initialValue: formData.limit_age || [20, 50]
          })(
            <Slider range tooltipVisible={true}/>
          )}
        </Item>
        <h3>其他设置</h3>
        <Item label="库存设置">
          {getFieldDecorator('stock', {
            initialValue: formData.stock
          })(
            <Input type="number" placeholder="设置库存"/>
          )}
        </Item>
        <Item label="生产备注">
          {getFieldDecorator('production_notes', {
            initialValue: formData.production_notes
          })(
            <Input placeholder="请输入生产备注"/>
          )}
        </Item>
        <Item label=" " colon={false}>
          <Button type="primary" loading={isBtnLoading} onClick={onSubmit}>保存</Button>
        </Item>
      </Form>
    </div>
  )
}

export default connect(null, dispatch => ({
  setBreadcrumb(value) {
    dispatch(actionCreators.setBreadCrumb(value))
  }
}))(Form.create()(withRouter(EditChannel)))
